const mysql = require('mysql2/promise');

class Survey {
    constructor() {
        // 直接使用MySQL连接配置
        this.pool = mysql.createPool({
            host: process.env.DB_HOST || 'localhost',
            port: parseInt(process.env.DB_PORT) || 3306,
            database: process.env.DB_NAME || 'qdkj',
            user: process.env.DB_USER || 'root',
            password: process.env.DB_PASSWORD || '',
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0,
            charset: 'utf8mb4'
        });
    }

    // 获取所有活跃的问卷
    async getAllActiveSurveys() {
        try {
            const [rows] = await this.pool.execute(
                'SELECT * FROM surveys WHERE status = ? ORDER BY created_at DESC',
                ['active']
            );
            return rows;
        } catch (error) {
            throw new Error(`获取问卷列表失败: ${error.message}`);
        }
    }

    // 根据ID获取问卷详情
    async getSurveyById(surveyId) {
        try {
            const [surveyRows] = await this.pool.execute(
                'SELECT * FROM surveys WHERE id = ? AND status = ?',
                [surveyId, 'active']
            );

            if (surveyRows.length === 0) {
                return null;
            }

            const survey = surveyRows[0];

            // 获取问卷题目
            const [questionRows] = await this.pool.execute(
                'SELECT * FROM survey_questions WHERE survey_id = ? ORDER BY question_order',
                [surveyId]
            );

            // 解析选项JSON
            const questions = questionRows.map(question => {
                let parsedOptions = null;
                if (question.options) {
                    try {
                        parsedOptions = JSON.parse(question.options);
                    } catch (parseError) {
                        console.error(`JSON解析失败 - 题目ID: ${question.id}, 选项: ${question.options}`, parseError);
                        // 如果JSON解析失败，尝试将字符串按逗号分割作为选项数组
                        if (typeof question.options === 'string') {
                            parsedOptions = question.options.split(',').map(opt => opt.trim());
                        } else {
                            parsedOptions = null;
                        }
                    }
                }
                return {
                    ...question,
                    options: parsedOptions
                };
            });

            return {
                ...survey,
                questions
            };
        } catch (error) {
            throw new Error(`获取问卷详情失败: ${error.message}`);
        }
    }

    // 获取随机问卷
    async getRandomSurvey() {
        try {
            const [rows] = await this.pool.execute(
                'SELECT * FROM surveys WHERE status = ? ORDER BY RAND() LIMIT 1',
                ['active']
            );

            if (rows.length === 0) {
                return null;
            }

            const survey = rows[0];
            return await this.getSurveyById(survey.id);
        } catch (error) {
            throw new Error(`获取随机问卷失败: ${error.message}`);
        }
    }

    // 提交问卷回答
    async submitSurveyResponse(studentId, surveyId, responseData, metadata = {}) {
        try {
            // 检查是否已经提交过
            const [existingRows] = await this.pool.execute(
                'SELECT id FROM survey_responses WHERE student_id = ? AND survey_id = ?',
                [studentId, surveyId]
            );

            if (existingRows.length > 0) {
                throw new Error('您已经提交过此问卷，无法重复提交');
            }

            // 插入回答记录
            const [result] = await this.pool.execute(
                `INSERT INTO survey_responses 
                (student_id, survey_id, response_data, completion_time, ip_address, user_agent) 
                VALUES (?, ?, ?, ?, ?, ?)`,
                [
                    studentId,
                    surveyId,
                    JSON.stringify(responseData),
                    metadata.completionTime || null,
                    metadata.ipAddress || null,
                    metadata.userAgent || null
                ]
            );

            return {
                id: result.insertId,
                message: '问卷提交成功'
            };
        } catch (error) {
            throw new Error(`提交问卷失败: ${error.message}`);
        }
    }

    // 检查学生是否已经完成某个问卷
    async hasStudentCompletedSurvey(studentId, surveyId) {
        try {
            // 首先检查问卷是否存在且活跃
            const [surveyRows] = await this.pool.execute(
                'SELECT id FROM surveys WHERE id = ? AND status = ?',
                [surveyId, 'active']
            );
            
            if (surveyRows.length === 0) {
                throw new Error('问卷不存在或已停用');
            }
            
            // 检查学生是否已完成问卷
            const [rows] = await this.pool.execute(
                'SELECT id FROM survey_responses WHERE student_id = ? AND survey_id = ? AND is_completed = ?',
                [studentId, surveyId, true]
            );
            return rows.length > 0;
        } catch (error) {
            throw new Error(`检查问卷完成状态失败: ${error.message}`);
        }
    }

    // 获取问卷统计信息
    async getSurveyStats(surveyId) {
        try {
            const [totalRows] = await this.pool.execute(
                'SELECT COUNT(*) as total FROM survey_responses WHERE survey_id = ?',
                [surveyId]
            );

            const [completedRows] = await this.pool.execute(
                'SELECT COUNT(*) as completed FROM survey_responses WHERE survey_id = ? AND is_completed = ?',
                [surveyId, true]
            );

            return {
                total: totalRows[0].total,
                completed: completedRows[0].completed
            };
        } catch (error) {
            throw new Error(`获取问卷统计失败: ${error.message}`);
        }
    }

    // 关闭数据库连接池
    async close() {
        await this.pool.end();
    }
}

module.exports = Survey;